/**
 * @fileOverview 事件源
 * @author <a href="mailto:lexloo@126.com">lexloo</a>
 */

(function() {
	if (typeof $XEventSource != 'undefined') {
		return;
	}

	$Namespace('com.firefly');

	/**
	 * 事件源
	 * 
	 * @class 事件源
	 * @version 1.0
	 * @author <a href="mailto:lexloo@126.com">lexloo</a>
	 * @constructor
	 */
	com.firefly.XEventSource = function() {
		this.initialize();
	};

	/**
	 * @private
	 */
	com.firefly.XEventSource.prototype.initialize = function() {
		this.eventListeners = null;
		/**
		 * 是否是否有效
		 * 
		 * @type {Boolean}
		 */
		this.eventsEnabled = true;
	};

	/**
	 * 添加事件监听
	 * 
	 * @param {String}
	 *            name 事件名
	 * @param {Function}
	 *            fn 监听函数
	 */
	com.firefly.XEventSource.prototype.addListener = function(name, fn) {
		if (this.eventListeners == null) {
			this.eventListeners = [];
		}

		this.eventListeners.push(name);
		this.eventListeners.push(fn);
	};

	/**
	 * 移除事件监听
	 * 
	 * @param fn
	 *            监听函数
	 */
	com.firefly.XEventSource.prototype.removeListener = function(fn) {
		if (this.eventListeners) {
			var i = 0;
			while (i < this.eventListeners.length) {
				if (this.eventListeners[i + 1] == fn) {
					this.eventListeners.splice(i, 2);
				} else {
					i += 2;
				}
			}
		}
	};

	/**
	 * 触发事件
	 * 
	 * @param evt
	 *            事件
	 * @param source
	 *            触发事件源
	 */
	com.firefly.XEventSource.prototype.fireEvent = function(evt, source) {
		if (this.eventListeners && this.eventsEnabled) {
			if (evt == null) {
				evt = new $XEventObject();
			}

			if (source == null) {
				source = this;
			}
			var args = [ source, evt ];
			for ( var i = 0; i < this.eventListeners.length; i += 2) {
				var listen = this.eventListeners[i];
				if (listen == null || listen == evt.getName()) {
					this.eventListeners[i + 1].apply(this, args);
				}
			}
		}
	};

	/**
	 * com.firefly.XEventSource的快捷访问
	 */
	$XEventSource = com.firefly.XEventSource;
})();